<?php

namespace App\Exception\Handler;

use Hyperf\Di\Annotation\Inject;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Psr\Http\Message\ResponseInterface;
use Throwable;
use Hyperf\Validation\ValidationException;

class ValidationExceptionHandler extends ExceptionHandler
{
    #[Inject]
    protected \Hyperf\HttpServer\Contract\ResponseInterface $response;
    public function handle(Throwable $throwable, ResponseInterface $response): ResponseInterface
    {
        $this->stopPropagation();
        $errors = @$throwable->validator->errors()->toArray();
        return $this->response->json([
            'code' => 400,
            'msg' => $throwable->validator->messages()->first(),
            'data' => $errors
        ]);
    }

    public function isValid(Throwable $throwable): bool
    {
        return $throwable instanceof ValidationException;
    }
}